package 二叉树;

import java.util.HashMap;
import java.util.Map;

public class LC_106从中序与后序遍历序列构造二叉树 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    Map<Integer,Integer> map;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map=new HashMap<>();
        for(int i=0;i<inorder.length;i++){
            map.put(inorder[i],i);
        }
        //左闭右开[)
        return findTree(inorder,0,inorder.length,postorder,0,postorder.length);
    }
    public  TreeNode findTree(int[] inorder,int inbegin,int inend,int[] postorder,int postbegin,int postend){
        if(inbegin>=inend||postbegin>=postend)
            return null;
        int rootindex=map.get(postorder[postend-1]);
        TreeNode root=new TreeNode(inorder[rootindex]);
        int len=rootindex-inbegin;//保存中序左子树个数
        root.left=findTree(inorder,inbegin,rootindex,postorder,postbegin,postbegin+len);
        root.right=findTree(inorder,rootindex+1,inend,postorder,postbegin+len,postend-1);
        return root;
    }
}
